package com.example.a2032.fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.a2032.R;
import com.example.a2032.Utils.Utils;
import com.example.a2032.activity.SettingActivity;
import com.example.a2032.activity.UnreadMsgActivity;
import com.example.a2032.adapter.TopAdapter;
import com.example.a2032.constant.DemoConstant;
import com.example.a2032.entity.RealTimeData;
import com.example.a2032.viewmodel.RealTimeStepViewModel;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.model.EaseEvent;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link TopFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TopFragment extends BaseFragment implements TopAdapter.onItemClickListener {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.RecyclerView_top)
    RecyclerView RecyclerViewTop;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private TopAdapter topAdapter;
    private RealTimeStepViewModel realTimeStepViewModel;
    private LiveData<RealTimeData> realTimeDataLiveData;

    public TopFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment TopFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static TopFragment newInstance() {
        TopFragment fragment = new TopFragment();
        Bundle args = new Bundle();
        //  args.putString(ARG_PARAM1, param1);
        //  args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_top, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {

        if (realTimeStepViewModel == null) {
            Log.i(TAG, "init: ");
            realTimeStepViewModel = new ViewModelProvider(getActivity()).get(RealTimeStepViewModel.class);
        }
        //  subscribe(this);
        List<String> list = new ArrayList<>();
        list.add(batteryValue != -1 ? batteryValue + "%" : "--");
        list.add("--");
        list.add("0 " + getString(R.string.msg));
        list.add(getString(R.string.setting));
        int[] resIds = Utils.getResourcesImageArray(getContext(), R.array.top_img_array);
        topAdapter = new TopAdapter(list, resIds);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        RecyclerViewTop.setLayoutManager(linearLayoutManager);
        RecyclerViewTop.setAdapter(topAdapter);
        topAdapter.setOnItemClickListener(this);
        getRealTimeData(Utils.getTodayTimeString());
       // getUnReadMsg();
    }

    void getUnReadMsg() {
        realTimeStepViewModel.homeUnReadObservable().observe(getActivity(), readCount -> {
            if (!isAdded()) return;
            topAdapter.updateUnReadMsg(readCount + getString(R.string.msg));
        });
        realTimeStepViewModel.checkUnreadMsg();
//        realTimeStepViewModel.messageChangeObservable().with(DemoConstant.GROUP_CHANGE, EaseEvent.class).observe(getActivity(), this::checkUnReadMsg);
//        realTimeStepViewModel.messageChangeObservable().with(DemoConstant.NOTIFY_CHANGE, EaseEvent.class).observe(getActivity(), this::checkUnReadMsg);
//        realTimeStepViewModel.messageChangeObservable().with(DemoConstant.MESSAGE_CHANGE_CHANGE, EaseEvent.class).observe(getActivity(), this::checkUnReadMsg);
//        realTimeStepViewModel.messageChangeObservable().with(DemoConstant.CONVERSATION_DELETE, EaseEvent.class).observe(getActivity(), this::checkUnReadMsg);
//        realTimeStepViewModel.messageChangeObservable().with(DemoConstant.CONTACT_CHANGE, EaseEvent.class).observe(getActivity(), this::checkUnReadMsg);
//        realTimeStepViewModel.messageChangeObservable().with(DemoConstant.CONVERSATION_READ, EaseEvent.class).observe(getActivity(), this::checkUnReadMsg);

    }

    private void checkUnReadMsg(EaseEvent event) {
        if (event == null) {
            return;
        }
        realTimeStepViewModel.checkUnreadMsg();
    }

    void getRealTimeData(String date) {
        realTimeDataLiveData = realTimeStepViewModel.getLastRealTime(date);
        realTimeDataLiveData.observe(getViewLifecycleOwner(), realTimeObserve);
    }

    androidx.lifecycle.Observer realTimeObserve = new androidx.lifecycle.Observer<RealTimeData>() {


        @Override
        public void onChanged(RealTimeData realTimeData) {
            Log.i(TAG, "onChanged: ");
            if (realTimeData != null) {
                updateStep(realTimeData.getSteps());
            }
        }
    };
    private static final String TAG = "TopFragment";

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Log.i(TAG, "onAttach: ");

    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "onResume: ");
        getRealTimeData(Utils.getTodayTimeString());
        getUnReadMsg();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        Log.i(TAG, "onHiddenChanged: " + hidden);
    }

    int batteryValue = -1;

    public void updateBatteryValue(int battery) {
        this.batteryValue = battery;
        if (!isAdded()) return;
        topAdapter.updateBattery(battery);
    }

    public void updateStep(int stepValue) {
        if (!isAdded()) return;
        topAdapter.updateStep(stepValue);
    }


    @Override
    public void onItemClick(int position) {
        if (position == 3) {
            startActivityWithTrans(SettingActivity.class, OpFragment.KEY_Title, getString(R.string.op_setting));
        } else if (position == 2) {
            int mscCount = EMClient.getInstance().chatManager().getUnreadMessageCount();
            if (mscCount != 0)
                startActivityWithTrans(UnreadMsgActivity.class, OpFragment.KEY_Title, getString(R.string.msg));
        }
    }
}